import { ResponseData } from "@scpun/core";
import Mock from "mockjs";
export function resultSuccess(result: any, { message = "ok" } = {}): ResponseData {
    return Mock.mock({
        code: 0,
        data: result,
        message,
    });
}

export function resultPageSuccess<T = any>(
    page: number,
    pageSize: number,
    items: T[],
    { message = "ok" } = {}
): ResponseData {
    const pageData = pagination(page, pageSize, items);

    return {
        ...resultSuccess({
            page,
            pageSize,
            total: items.length,
            items: pageData,
        }),
        message,
    };
}

export function pagination<T = any>(pageNo: number, pageSize: number, array: T[]): T[] {
    const offset = (pageNo - 1) * Number(pageSize);
    const ret =
        offset + Number(pageSize) >= array.length
            ? array.slice(offset, array.length)
            : array.slice(offset, offset + Number(pageSize));
    return ret;
}

export function doCustomTimes(times: number, callback: any) {
    let i = -1;
    while (++i < times) {
        callback(i);
    }
}

export function getRequestToken({ headers }: requestParams) {
    return headers?.authorization;
}

export interface requestParams {
    method: string;
    body: any;
    headers?: { authorization?: string };
    query: any;
}

export function resultError(message = "Request failed", { code = -1, result = null } = {}) {
    return {
        code,
        data: result,
        message,
        path: "",
    };
}
